#include "recvfile.h"
#include <QHostAddress>
#include <QDebug>
#include <QThread>
#include <QtEndian>
#include <QDataStream>

RecvFile::RecvFile(QObject *parent) : QObject(parent)
{

}

RecvFile::~RecvFile()
{
    //销毁套接字
    m_tcp->close();
    m_tcp->deleteLater();

}

void RecvFile::connectServer(QString ip, unsigned short port)
{
    qDebug()<<"当子线程线程ID:"<<QThread::currentThreadId();
    // 连接服务器
    m_tcp = new QTcpSocket;
    //连接服务器
    m_tcp->connectToHost(QHostAddress(ip),port);
    connect(m_tcp,&QTcpSocket::connected,this,&RecvFile::connectOK); //成功建立连接，发送连接成功对象
    //接受到数据， 服务器发送给客户端数据完整之后
    connect(m_tcp,&QTcpSocket::readyRead,this,[=]()
            {
                //读取文件总大小
                if(first_total)
                {
                    first_total = false;
                    QByteArray array =  m_tcp->readLine();
                    qDebug()<<"array传入文件大小为:"<<array.data();
                    emit total_size_signal(array.toInt());
                }
                //QByteArray all = m_tcp->readAll();
                //        emit message(all);
                //对数据进行拆包
                else {
                    dealData();

                    emit gameover();
                }
            });
}

void RecvFile::dealData()
{
    int totalBytes = 0;
    int recvBytes = 0;
    QByteArray block; //存储对应的数据块

    //判断有没有数据
    if(m_tcp->bytesAvailable() == 0)
    {
        qDebug()<<"没有数据咯";
        return ;
    }
    //读包头 可读的字节大于4个字节 //包头只可以读取字节，无法获取总字节
    if(static_cast<int>(m_tcp->bytesAvailable()) >= static_cast<int>(sizeof (int)))
    {

        QByteArray head = m_tcp->read(sizeof(int));
        totalBytes = qFromBigEndian(*reinterpret_cast<int*>(head.data()));
        //qDebug() << "接收方包头的长度: " << totalBytes;
    }
    else {

        return;  //递归 也会结束
    }
    //根据包头去读 数据块
    while(totalBytes-recvBytes >0 &&m_tcp->bytesAvailable() > 0)
    {
        block.append( m_tcp->read(totalBytes-recvBytes));
        recvBytes = block.size();
        nowsize +=recvBytes;
        emit now_size_signal(nowsize);
    }
    if(totalBytes == recvBytes)
    {

        emit message(block);

    }
    //如果还有数据
    if(m_tcp->bytesAvailable() > 0)
    {
        qDebug()<<"开始 递归调用....";
        dealData();
    }
}
